//
//  LGBloodGlucoseChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/6.
//

#import "LGBloodGlucoseChart.h"

#import "LGScrollView.h"
#define topMargin     viewPix(50)

#define leftMargin     viewPix(35)+iPadMargin(10)

#define lineHeight     viewPix(30)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight   (lineHeight*8+viewPix(20))

#define buttonMargin   (Screen_W-viewPix(32)-viewPix(42)-viewPix(284)-iPadMargin(40))/2.0

@interface LGBloodGlucoseChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**  偏高 */
@property (nonatomic , strong)UIButton *highButton;
/**  正常 */
@property (nonatomic , strong)UIButton *normalButton;
/**  偏低 */
@property (nonatomic , strong)UIButton *lowButton;
/**  全部 */
@property (nonatomic , strong)UIButton *allButton;
/**  餐前 */
@property (nonatomic , strong)UIButton *beforButton;
/**  餐后、睡前 */
@property (nonatomic , strong)UIButton *afterButton;
/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**  空腹 */
@property (nonatomic , strong)NSArray *itemArray1;
/**  早餐后 */
@property (nonatomic , strong)NSArray *itemArray2;
/**  午餐前 */
@property (nonatomic , strong)NSArray *itemArray3;
/**  午餐后 */
@property (nonatomic , strong)NSArray *itemArray4;
/**  晚餐前 */
@property (nonatomic , strong)NSArray *itemArray5;
/**  晚餐后 */
@property (nonatomic , strong)NSArray *itemArray6;
/**  睡前 */
@property (nonatomic , strong)NSArray *itemArray7;
/**   */
@property (nonatomic , strong)NSArray *itemArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , strong)NSDictionary *statusDic;
/**   */
@property (nonatomic , strong)NSArray *titleArray;

@end

@implementation LGBloodGlucoseChart

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.statusDic = @{@"0":@"血糖-正常",@"1":@"血糖-偏高",@"2":@"血糖-偏低"};
        self.titleArray = @[@"空腹",@"早餐后",@"午餐后",@"晚餐后"];
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0) {
        self.totalCount = [dataDic[@"xAxis"] count];
        NSInteger count = (self.totalCount>7)?7:self.totalCount;
        self.itemWidth = (count>0)?scrollWidth/count:scrollWidth;
        self.scrollView.contentSize = CGSizeMake(viewPix(20)+self.itemWidth*self.totalCount, scrollHeight);
        [self.scrollView setContentOffset:CGPointMake(viewPix(20)+self.itemWidth*self.totalCount-scrollWidth-viewPix(10), 0)];
        self.dayArray = dataDic[@"xAxis"];
        self.itemArray1 = dataDic[@"seriesA_fbg"];
        self.itemArray2 = dataDic[@"seriesA_pbg"];
        self.itemArray3 = dataDic[@"seriesB_pbg"];
        self.itemArray4 = dataDic[@"seriesC_pbg"];
        self.itemArray = @[dataDic[@"seriesA_fbg"],dataDic[@"seriesA_pbg"],dataDic[@"seriesB_pbg"],dataDic[@"seriesC_pbg"]];
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*7.5, self.itemWidth, lineHeight);
        [self.scrollView addSubview:dayLabel];
    }
}

-(void)setItemArray:(NSArray *)itemArray{
    _itemArray = itemArray;
    for (NSInteger i=0; i<itemArray.count; i++) {
        NSArray *tempArray = itemArray[i];
        
        for (NSInteger j=0; j<tempArray.count; j++) {
            NSDictionary *itemDic = tempArray[j];
            if([itemDic[@"status"] integerValue] != -1){
                NSString *status = self.statusDic[LGNSString(itemDic[@"status"])];
                NSString *normalPic = [NSString stringWithFormat:@"%@Normal",status];
                NSString *selectPic = [NSString stringWithFormat:@"%@Select",status];
                CGFloat pointY = scrollHeight-([itemDic[@"value"] floatValue]/5.0*lineHeight+viewPix(20)+lineHeight*0.5);
                UIButton *button = [UIButton buttonWithImage:normalPic selectImage:selectPic];
                button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
                button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*j, pointY);
                button.tag = 1000*(i+1)+j;
                [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
                [self.scrollView addSubview:button];
            }
        }
    }
}


//筛选数据：全部、空腹、餐后
-(void)typeButtonTouched:(UIButton *)sender{
    sender.selected = YES;
    if(sender == self.allButton){
        //全部
        self.beforButton.selected = NO;
        self.afterButton.selected = NO;
        for (NSInteger i=0; i<self.itemArray.count; i++) {
            for (NSInteger j=0; j<self.totalCount; j++) {
                UIButton *button = [self viewWithTag:1000*(i+1)+j];
                button.hidden = NO;
            }
        }
        
    }else if (sender == self.beforButton){
        //空腹
        self.allButton.selected = NO;
        self.afterButton.selected = NO;

        for (NSInteger i=0; i<self.itemArray.count; i++) {
            if(i == 0){
                for (NSInteger j=0; j<self.totalCount; j++) {
                    UIButton *button = [self viewWithTag:1000*(i+1)+j];
                    button.hidden = NO;
                }
            }else{
                for (NSInteger j=0; j<self.totalCount; j++) {
                    UIButton *button = [self viewWithTag:1000*(i+1)+j];
                    button.hidden = YES;
                }
            }
            
        }
        
    }else if (sender == self.afterButton){
        //睡前、餐后2h
        self.allButton.selected = NO;
        self.beforButton.selected = NO;
        
        for (NSInteger i=0; i<self.itemArray.count; i++) {
            if(i > 0){
                for (NSInteger j=0; j<self.totalCount; j++) {
                    UIButton *button = [self viewWithTag:1000*(i+1)+j];
                    button.hidden = NO;
                }
            }else{
                for (NSInteger j=0; j<self.totalCount; j++) {
                    UIButton *button = [self viewWithTag:1000*(i+1)+j];
                    button.hidden = YES;
                }
            }
        }
    }
}

-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    NSMutableArray *selectArray = [NSMutableArray array];
    for (NSInteger i=0; i<self.itemArray.count; i++) {
        NSArray *tempArray = self.itemArray[i];
        for (NSInteger j=0; j<tempArray.count; j++) {
            NSDictionary *tempDic = tempArray[j];
            if([tempDic[@"status"] integerValue] != -1){
                UIButton *button = [self viewWithTag:1000*(i+1)+j];
                button.selected = (index == j)?YES:NO;
                if(index == j){
                    NSString *score = LGNSString(tempDic[@"value"]);
                    NSString *status = LGNSString(tempDic[@"status"]);
                    NSDictionary *statusDic = @{@"0":@"normal",@"1":@"high",@"2":@"low"};
                    [selectArray addObject:@{@"title":self.titleArray[i],@"score":score,@"status":statusDic[status]}];
                }
            }
        }
    }
    
    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
        [self.delegate showAlertView:selectArray date:self.dayArray[index] point:point];
    }
    
    CGPoint point2 = [self.scrollView convertPoint:sender.center toView:self.superview.superview.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView2:date:point:)]){
        [self.delegate showAlertView2:selectArray date:self.dayArray[index] point:point2];
    }
}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)createSubView{
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self addSubview:self.titleBtn];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.highButton];
    [self.baseView addSubview:self.normalButton];
    [self.baseView addSubview:self.lowButton];
    [self.baseView addSubview:self.allButton];
    [self.baseView addSubview:self.beforButton];
    [self.baseView addSubview:self.afterButton];
    NSArray *titleArray = @[@"35",@"30",@"25",@"20",@"15",@"10",@"5",@"0"];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(20), lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    [self.titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.baseView.mas_top).offset(12);
        make.left.right.equalTo(self.baseView);
        make.height.equalTo(@(viewPix(40)));
    }];
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(20), viewPix(7), viewPix(100), viewPix(23));
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(87))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 10;
    }
    return _baseView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:@"血糖" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#282828" frame:CGRectMake(0, kMinY(self.baseView.frame), Screen_W-viewPix(32), viewPix(40))];
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, 0);
        _titleBtn.backgroundColor = [UIColor whiteColor];
        _titleBtn.cornerRidus = 10;
        _titleBtn.hidden = YES;
        UIImageView *tipView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(32)-viewPix(28), viewPix(12), viewPix(16), viewPix(16))];
        tipView.image = [UIImage imageNamed:@"grayTip16"];
        [_titleBtn addSubview:tipView];
    }
    return _titleBtn;
}

-(UILabel *)dayLabel{
    if(!_dayLabel){
        _dayLabel = [UILabel lableWithText:@"最近30天血糖分布" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _dayLabel.frame = CGRectMake(viewPix(12), viewPix(14), viewPix(200), viewPix(23));
    }
    return _dayLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"mmol/L" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(3, topMargin-12, 50, viewPix(17));
    }
    return _unitLabel;
}

-(UIButton *)highButton{
    if(!_highButton){
        _highButton = [UIButton buttonWithTitle:@" 偏高" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血糖-偏高"];
        _highButton.frame = CGRectMake(viewPix(55), kMaxY(self.scrollView.frame), viewPix(50), viewPix(22));
        _highButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    }
    return _highButton;
}

-(UIButton *)normalButton{
    if(!_normalButton){
        _normalButton = [UIButton buttonWithTitle:@" 正常" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血糖-正常"];
        _normalButton.frame = CGRectMake((Screen_W-viewPix(32)-viewPix(50))/2.0, kMinY(self.highButton.frame), viewPix(50), viewPix(22));
        _normalButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    }
    return _normalButton;
}

-(UIButton *)lowButton{
    if(!_lowButton){
        _lowButton = [UIButton buttonWithTitle:@" 偏低" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血糖-偏低"];
        _lowButton.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(110), kMinY(self.highButton.frame), viewPix(50), viewPix(22));
        _lowButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    }
    return _lowButton;
}

-(UIButton *)allButton{
    if(!_allButton){
        _allButton = [UIButton buttonWithTitle:@"全部" titleFont:LGFont(14) normalColor:@"#999999" selectColor:kThemeColor];
        _allButton.frame = CGRectMake(viewPix(20), kMaxY(self.highButton.frame)+viewPix(17), viewPix(78), viewPix(32));
        _allButton.cornerRidus = viewPix(16);
        _allButton.selected = YES;
        [_allButton setBackgroundColor:[UIColor colorWithString:@"#EFEFEF"] forState:UIControlStateNormal];
        [_allButton setBackgroundColor:[UIColor colorWithString:@"#E5F1FF"] forState:UIControlStateSelected];
        [_allButton addTarget:self action:@selector(typeButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allButton;
}

-(UIButton *)beforButton{
    if(!_beforButton){
        _beforButton = [UIButton buttonWithTitle:@"空腹" titleFont:LGFont(14) normalColor:@"#999999" selectColor:kThemeColor];
        _beforButton.frame = CGRectMake(kMaxX(self.allButton.frame)+buttonMargin, kMinY(self.allButton.frame), viewPix(103)+iPadMargin(20), viewPix(32));
        _beforButton.cornerRidus = viewPix(16);
        [_beforButton setBackgroundColor:[UIColor colorWithString:@"#EFEFEF"] forState:UIControlStateNormal];
        [_beforButton setBackgroundColor:[UIColor colorWithString:@"#E5F1FF"] forState:UIControlStateSelected];
        [_beforButton addTarget:self action:@selector(typeButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _beforButton;
}

-(UIButton *)afterButton{
    if(!_afterButton){
        _afterButton = [UIButton buttonWithTitle:@"餐后2h" titleFont:LGFont(14) normalColor:@"#999999" selectColor:kThemeColor];
        _afterButton.frame = CGRectMake(kMaxX(self.beforButton.frame)+buttonMargin, kMinY(self.allButton.frame), viewPix(103)+iPadMargin(20), viewPix(32));
        _afterButton.cornerRidus = viewPix(16);
        [_afterButton setBackgroundColor:[UIColor colorWithString:@"#EFEFEF"] forState:UIControlStateNormal];
        [_afterButton setBackgroundColor:[UIColor colorWithString:@"#E5F1FF"] forState:UIControlStateSelected];
        [_afterButton addTarget:self action:@selector(typeButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _afterButton;
}

@end
